<template>
  <BasicModal title="排期销售" @register="registerModal"
              :canFullscreen="false" :centered="true" :destroyOnClose="true" :maskClosable="false" 
              :showCancelBtn="false" :showOkBtn="false" :width="'90%'" 
              :bodyStyle="{height:'calc(100vh - 120px)', overflow:'hidden'}"
  >
    <!-- 查询区域 -->
    <div class="jeecg-basic-table jeecg-basic-table-form-container">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">

          <!-- 有些系统是4个字 -->
          <a-col flex="160px">
            <a-form-item label="出港" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
              <a-select
                v-model:value="queryParam.schepostId"
                style="width: 100px"
                :defaultActiveFirstOption="false"
                :allowClear="true"
                :options="scheposts"
              ></a-select>
            </a-form-item>
          </a-col>

          <a-col flex="280px">
            <a-form-item label="日期" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ style: { width: '245px' } }">
              <a-date-picker
                v-model:value="queryParam.beginDate"
                :disabled-date="disabledStartDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 105px; padding: 4px;"
              /> ~
              <a-date-picker
                v-model:value="queryParam.endDate"
                :disabled-date="disabledEndDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 108px; padding: 4px;" O
              />
            </a-form-item>
          </a-col>

          <a-col flex="280px">
            <a-form-item label="有订单" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '150px' } }">
              <a-checkbox :aria-checked="queryParam.haveOrder" @change="changeHaveOrder"></a-checkbox>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float:right; width:90px; margin-right: 0px;">
            <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" color="success" @click="preBtnQuery()" class="mr-4px">上月</a-button>
              <a-button type="primary" color="success" @click="nexBtnQuery()" class="mr-4px">下月</a-button>
              <a-button type="primary" color="success" @click="curBtnQuery()" class="mr-4px">本月</a-button>
              <a-button type="primary" @click="searchQuery" preIcon="ant-design:search" class="mr-4px">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <BasicTable @register="registerTable" :onRowClick="handleClick" :rowClassName="rowClassName"></BasicTable>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, toRaw, unref, reactive, watch, onMounted, nextTick } from "vue";

  import { BasicModal, useModalInner } from "/@/components/Modal";
  import { BasicTable, TableAction, ActionItem, BasicColumn, useTable} from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { render } from '/@/utils/common/renderUtils';
  import { residueList } from "/@/views/weixin/article/artticle.api";
  import { filterObj } from '/@/utils/common/compUtils';
  import { replaceAll } from "/@/utils";
  import moment from 'dayjs'
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';

  // 定义查询 - 查询条件
  const loading   = ref(false);
  const scheposts = reactive<any>([]);
  const index     = ref(0);

  //初始化 -------------------------------------------------------------
  //定义查询表单，查询条件
  const queryParam = reactive({
    articleId: '',
    schepostId: '',
    schepost: [],
    beginDate: moment().subtract( 0, 'months').format('YYYY-MM-01'),
    endDate: moment().add( 0, 'months').endOf('month').format('YYYY-MM-DD'),
    haveOrder: false,
  })

  //限制查询日期，开始日期不能大于结束日期
  function disabledStartDate(beginDate) {
    const endDate = queryParam.endDate;
    if (!beginDate || !endDate) {
      return false;
    }
    return beginDate.valueOf() > moment(endDate).valueOf()
  }

  function disabledEndDate(endDate) {
    const beginDate = queryParam.beginDate;
    if (!endDate || !beginDate) {
      return false;
    }
    return moment(beginDate).valueOf() > endDate.valueOf();
  }

  function changeHaveOrder(e) {
    queryParam.haveOrder = e.target.checked;
  }

  function searchReset() {
    Object.assign(queryParam, {
      schepostId: '',
      schepost: [],
      beginDate: moment().subtract( 0, 'months').format('YYYY-MM-01'),
      endDate: moment().add( 0, 'months').endOf('month').format('YYYY-MM-DD'),
      haveOrder: false,
    });
  }

  //初始化 -------------------------------------------------------------

  //表单赋值
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    queryParam.articleId = data.id;
    searchReset();
    searchQuery();
  });

  // ----------列表数据-开始--------------------------------------------------------------
  // 出港地点
  const schepostFmt = ({ text }: { text: any }) => {
    if (text && text !== '合计') {
      return replaceAll(text, '出港', '');
    } else  {
      return '南宁'
    }
  };
  // 机位
  const seatFmt = ({ text }: { text: any }) => {
    if (text == '0') {
      return '现询';
    } else  {
      return text;
    }
  };
  // 出团人数
  const numberFmt = ({ text, record }) => {
    var value = "";
    if (!!record.adultNo) {
      value = record.adultNo
    } else {
      value = "0";
    }
    if (record.childNo) {
      value = value + "|" + record.childNo
    } else {
      value = value + "|0";
    }
    if (record.escortNo) {
      value = value + "|" + record.escortNo
    } else {
      value = value + "|0";
    }
    return value;
  };
  // 余位
  const resiFmt = ({ text, record }: { text: any, record: any }) => {
    if (record.seat == '0') {
      return '现询';
    } else  {
      if (!text) {
        return '0';
      } else {
        return text;
      }
    }
  };
  // 订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '出港', align: 'center', dataIndex: 'schepost', width: 56, customRender: schepostFmt },
    { title: '出团日期', align: 'center', dataIndex: 'tourDate', width: 100 },
    { title: '星期', align: 'center', dataIndex: 'weekName', width: 70 },
    { title: '成人价', align: 'right', dataIndex: 'price', width: 90, className: 'text-red-500' },
    { title: '儿童价', align: 'right', dataIndex: 'priceChild', width: 90, className: 'text-red-500'  },
    { title: '同行返', align: 'right', dataIndex: 'priceVip', width: 80, className: 'text-green-500' },
    { title: '会员返', align: 'right', dataIndex: 'priceRoom', width: 80, className: 'text-green-500' },
    { title: '机位', align: 'center', dataIndex: 'seat', width: 60, customRender: seatFmt },
    { title: '出团人数', align: 'center', dataIndex: 'number', width: 85, customRender: numberFmt },
    { title: '余位', align: 'center', dataIndex: 'resi', width: 60, customRender: resiFmt },
    { title: '应付团款', align: 'right', dataIndex: 'ygs', width: 85, className: 'text-red-500' },
    { title: '优惠金额', align: 'right', dataIndex: 'yhj', width: 85, className: 'text-green-500' },
  ];

  // 列表页面公共参数、方法
  const dataSource = ref<any[]>([]);
  const summaryData = ref<any[]>([]);
  const { prefixCls, tableContext } = useListPage({
    designScope: 'bankDecompose-list',
    tableProps: {
      rowKey: '(row) => row.id',
      size: "small",
      api: residueList,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: true,    //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 20,
      showSummary: true,
      summaryFunc: handleSummary,
      beforeFetch: (params) => {Object.assign(params, unref(queryParam))}, 
    }
  });

  // 注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;

  // --------------组件--事件----------------------------------------

  //单击行
  let selectRows = reactive<any>({ id: '', username: '' });
  function handleClick(record) {
    selectRows.id = record.id;
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  /**
   * 查询
   */
  function searchQuery() {
    setProps({searchInfo:toRaw(queryParam)});
    reload()
  }

  // 上月
  function preBtnQuery() {
    ++index.value
    queryParam.beginDate = moment().subtract( index.value, 'months').format('YYYY-MM-01')
    queryParam.endDate = moment().subtract( index.value, 'months').endOf('month').format('YYYY-MM-DD')
    searchQuery()
  }

  // 下月
  function nexBtnQuery() {
    --index.value
    queryParam.beginDate = moment().subtract( index.value, 'months').format('YYYY-MM-01')
    queryParam.endDate = moment().subtract( index.value, 'months').endOf('month').format('YYYY-MM-DD')
    searchQuery()
  }

  // 本月-
  function curBtnQuery() {
    index.value = 0
    queryParam.beginDate = moment().subtract( index.value, 'months').format('YYYY-MM-01')
    queryParam.endDate = moment().subtract( index.value, 'months').endOf('month').format('YYYY-MM-DD')
    searchQuery()
  }

  /**
   * 获取后台数据
   */
  async function loadRootData() {
    loading.value = true;
    await residueList(filterObj(queryParam)).then( res => {
      if (res) {
        dataSource.value = res.rows;
        summaryData.value = res.footer;
      } else {
        dataSource.value = [];
        summaryData.value = [];
      }
    }).finally(() => {
      loading.value = false;
    });
    console.info('loadRootData@@@@', summaryData.value)
  }

  /**
   * 拆分出统计数据
   * @param tableData 
   */
  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource()
    redoHeight();
    if (res) {
      Object.assign(scheposts, res.scheposts);
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }
  // --------------组件--事件----------------------------------------
</script>

<style lang="less" scoped>

</style>
